<!-- <template>
  <div class="app-container">

    <el-table
    border
    stripe
    show-header
    v-loading="listLoading"
    element-loading-text="Loading"
    fit
    size="small"
    highlight-current-row
    :data="tableData.filter(data => !search || data.address.toLowerCase().includes(search.toLowerCase()))"
    style="width: 100%">
    <el-table-column
    width="100px"
      label="ID"
      prop="id">
    </el-table-column>
    <el-table-column
    width="150px"
      label="PLC名称"
      prop="plc">
    </el-table-column>
    <el-table-column
      label="地址"
      width="250px"
      prop="address">
      <template slot="header" slot-scope="scope" >
        <div >
          <span>地址</span>
          <el-input
          v-model="search"
          size="small"
          placeholder="输入关键字搜索"/>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      width="100px"
      label="类型"
      prop="type">
    </el-table-column>
    <el-table-column
      label="实际值"
      prop="value">
    </el-table-column>
    <el-table-column
      label="时间"
      prop="date">
    </el-table-column>
    <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag>
        </template>
      </el-table-column>
    <el-table-column
      label="描述"
      prop="desc">
    </el-table-column>
    <el-table-column
      align="right">
      <template slot="header" slot-scope="scope" >
          <el-button size="small" icon="el-icon-download" @click="handDownloadBatch(tableData)">批量下载</el-button>
          <el-button size="small" icon="el-icon-upload2" disabled @click="handUploadBatch()" >批量上传</el-button>
      </template>
      <template slot-scope="scope">
        <el-button
          size="small"
          icon="el-icon-edit"
          @click="handleEdit(scope.$index, scope.row)">修改</el-button>
        <el-button
          size="small"
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  </div>
</template>

<script>
import { getWriteData,setWriteData ,delTableList,downloadTableList ,uploadTableList } from '@/api/table'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        active: 'success',
        inactive: 'info',
        error: 'danger',
        warning: 'warning',
        success: 'success',
      }
      return statusMap[status]
    }
  },
  data() {
      return {
        listLoading: true,
        tableData: [],
        search: ''
      }
    },
    created() {
      this.fetchData()
    },

    methods: {
      fetchData() {
      // connPLC()
      this.listLoading = true
      getWriteData().then(response => {
        console.log(response.data.items)
        this.tableData = response.data.items
        this.listLoading = false
        })
      },

      handleEdit(index, row) {

        // //parameter in req.query
        // setWriteData(
        // {
        // 'value': row.value ,
        // 'id': row.id,
        // })
        // this.fetchData()
        // console.log(index, row);      open() {
          this.$prompt('值输入', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            //支持最长5为 可以有小数点 小数点后最多2位
            //250.25 OK
            //250.230 NG
            //2500000.25 NG
            inputPattern: /(^[1-9]([0-9]{1,5})?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            inputErrorMessage: '数据格式不正确'
          }).then(({ value }) => {

            if(row.status == 'active'){
              setWriteData(
              {
              'value': value ,
              'id': row.id,
              'address': row.address
              })

              this.fetchData()
              console.log(index, row);

              this.$message({
                type: 'success',
                message: '修改值为: ' + value
              });
            }else{

              this.$message({
                type: 'info',
                message: '该节点未激活'
              });

            }


          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            });
          });
      },
      handleDelete(index, row) {

        this.$confirm('是否删除该节点数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delTableList(
          {
          'id': row.id,
          })
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        console.log(index, row);
      },

      handDownloadBatch(list){
        this.listLoading = true
        this.timer = setInterval(() => {
          downloadTableList(list).then(response => {
          console.log(response)
          this.listLoading = false
          clearInterval(this.timer);
          })
          console.log("Table定时器启动")
        }, 1 * 1000);

      }

    },

    //切换页面后清除定时器
    beforeDestroy() {
      console.log("Table定时器启动")
      clearInterval(this.timer);
    }

}
</script>
 -->

 <template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.address" placeholder="S7 地址" style="width: 200px; " class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.status" placeholder="设备状态" clearable class="filter-item" style="width: 200px; margin-left: 10px ; margin-right: 10px;">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handDownloadBatch()">
        下载到PLC
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" disabled>
        从PLC上传
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.date | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="PLC 名称" min-width="100px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.plc }}</span>
          <el-tag style="margin-left: 5px;">PRO</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="S7 地址" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column label="节点类型" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际值" width="110px" align="center">
        <template slot-scope="{row}">
          <el-link type="primary">{{ row.value }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" min-width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作"  min-width="100px">
      <template slot-scope="scope">
        <el-button
          size="small"
          icon="el-icon-edit"
          @click="handleEdit(scope.$index, scope.row)">修改</el-button>
        <el-button
          size="small"
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { getList, getWriteData, setWriteData, uploadTableList, downloadTableList, delTableList } from '@/api/table'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: '激活', display_name: '节点激活' },
  { key: '未激活', display_name: '节点未激活' },
  { key: '故障', display_name: '故障' },
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        激活: 'success',
        未激活: 'info',
        故障: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        address: undefined,
        status: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      showReviewer: false,
      temp: {
        id: undefined,
        plc: '',
        address: '',
        type: '',
        value: '',
        status: '',
        rw: '',
        property: '',
        description: '',
        date: parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getWriteData(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleEdit(index, row) {
      this.$prompt('值输入', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        //支持最长5为 可以有小数点 小数点后最多2位
        //250.25 OK
        //250.230 NG
        //2500000.25 NG
        inputPattern: /(^[1-9]([0-9]{1,5})?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
        inputErrorMessage: '数据格式不正确'
      }).then(({ value }) => {

        if(row.status == '激活'){
          setWriteData(
          {
          'value': value ,
          'id': row.id,
          'address': row.address
          })

          this.fetchData()
          console.log(index, row);

          this.$message({
            type: 'success',
            message: '修改值为: ' + value
          });
        }else{

          this.$message({
            type: 'info',
            message: '该节点未激活'
          });

        }


      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
      console.log(index, row);
    },
    handleDelete(index, row) {

      this.$confirm('是否删除该节点数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTableList(
        {
        'id': row.id,
        })
        this.fetchData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

      console.log(index, row);
    },

    handDownloadBatch(){
      let list = this.list
      this.listLoading = true
      console.log(list)
      // this.timer = setInterval(() => {
      //   downloadTableList(list).then(response => {
      //   console.log(response)
      //   this.listLoading = false
      //   clearInterval(this.timer);
      //   })
      //   console.log("Table定时器启动")
      // }, 1 * 1000);
      downloadTableList(list).then(response => {
        console.log(response)
        this.listLoading = false
      })

    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        plc: '',
        address: '',
        type: '',
        value: '',
        status: '',
        rw: '',
        property: '',
        description: '',
        date: parseTime(new Date(),'{y}-{m}-{d} {h}:{i}:{s}'),
      }
    },

    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '时间', 'PLC 名称', 'S7 地址', '节点类型', '实际值', '节点状态', '描述']
        const filterVal = ['id', 'date', 'plc', 'address', 'type', 'actual', 'status', 'description']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'device-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'date') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
